package cn.telling.product.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.telling.common.util.CheckExcel;
import cn.telling.common.util.ExcelUtils;
import cn.telling.common.util.TellingConstance;
import cn.telling.product.dao.IBuyerDao;
import cn.telling.product.dao.IDirectionalDao;
import cn.telling.product.service.IDirectionalService;
import cn.telling.product.vo.AreaInfoVo;
import cn.telling.product.vo.BuyerVo;
import cn.telling.product.vo.StoreProductVo;
import cn.telling.product.vo.SupplyArea0Vo;
import cn.telling.sellerCenter.vo.ProductMainVO;
import cn.telling.sellercentre.dao.IProductMainDao;
import cn.telling.utils.StringHelperTools;

/**
 * 
 * @ClassName: DirectionalServiceImpl 
 * @Description: 产品定向发布业务服务接口的实现
 * @author 陈赟 
 * @date 2015年6月16日 下午4:30:43 
 *
 */
@Service("directionalService")
public class DirectionalServiceImpl implements IDirectionalService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(DirectionalServiceImpl.class);
    
	@Autowired
	@Qualifier("directionalDao")
	private IDirectionalDao directionalDao;
	
	@Autowired
    @Qualifier("buyerDao")
    private IBuyerDao buyerDao;

    @Autowired
    @Qualifier("productMainDao")
    private IProductMainDao productMainDao;
	
	@Override
    public List<Map<String, String>> getProductList(String supplyId, String sortId1, String sortId2, String productName,String parentBrand,String childBrand) {
        return directionalDao.getProductList(supplyId, sortId1, sortId2, productName,parentBrand,childBrand);
    }
	
	@Override
    public List<AreaInfoVo> getAreaLsByAreaId(String areaId, String level) {
        return directionalDao.getAreaLsByAreaId(areaId, level);
    }

    @Override
    public List<StoreProductVo> getProvinceStoreProductVo(String productId, String areaId) {
        return directionalDao.getProvinceStoreProductVo(productId, areaId);
    }

    @Override
    public List<AreaInfoVo> getSupplyArea(String supplyId) {
        return directionalDao.getSupplyArea(supplyId, TellingConstance.AREAROOT);
    }

    @Override
    public List<BuyerVo> getBuyerinfoVo(String areaId, Map<String, String> buyerTypeMap) {
        return directionalDao.getBuyerinfoVo(areaId, buyerTypeMap);
    }

    @Override
    public List<BuyerVo> importBuyerByExcel(InputStream is) {
        // EXCEL列名称对应的VO属性名称列表
        List<String> excelColumnNames = new ArrayList<String>();
        // 导入的EXCEL只有一列：客户简称
        excelColumnNames.add(BUYER_NAME);
        try {
            // 获取导入的EXCEL中的数据
            List<Map<String, String>> data = ExcelUtils.getImportData(is, excelColumnNames);
            // 将数据转换成BuyerVo列表
            List<BuyerVo> buyerList = ExcelUtils.makeData(data, BuyerVo.class, excelColumnNames, new CheckExcel() {

                @Override
                public boolean check(Map<String, String> data) {
                    return true;
                }
                
            });
            return buyerList;
        } catch (Exception e) {
            LOGGER.error("定向产品发布页面-选择买家页面-导入买家-读取EXCEL数据异常：", e);;
            return null;
        }
    }
    
    @Override
    public String checkImportBuyer(List<BuyerVo> supplyId, List<BuyerVo> buyerList) {
        //TODO 查出所有供应商销售区域内的买家
        //List<BuyerVo> list = buyerDao.getBuyerBySupplyId(supplyId);
        // 买家客户简称在生效的买家中是否存在
        // 先从查出的买家中取出客户简称
    	 
    	   String notExistBuyer = "";// 所有不存在的买家在EXCEL中所在行数
    		List<String> nameList = new ArrayList<String>();
            for(BuyerVo vo : supplyId) {
                nameList.add(vo.getShopname());
            }
            int num=0;
        try{
            for(int i=0; i<buyerList.size(); i++) {
            	num=i+2;
                String shortcompanyname = buyerList.get(i).getShortcompanyname();
                if(!nameList.contains(shortcompanyname)) {
                	
               
                    if(!"".equals(notExistBuyer)) {
                        notExistBuyer += ","+num;
                    }else{
                        notExistBuyer += "第"+num;
                    }                     
                }
            }              
          notExistBuyer+="行用户数据有误，请检查！"+"\n" +"可能原因：\n1.用户名在系统中不存在  \n2.用户不在您选择的区域内  \n3.用户不在您可销售的买家类型内";  
 
          if(buyerList==null||buyerList.size()==0){
        	   
        	   notExistBuyer+="不符合要求！" ;   //如果没有一个符合的条件那就不提示导入成功
           } 
           
       }catch(Exception e){
    		e.printStackTrace();
    		notExistBuyer="第"+num+"行用户不在您所选择的销售区域内，请检查！";
       }
      if(notExistBuyer.startsWith("行用户数据有误，请检查！")){
        	
        	notExistBuyer="";
       }      
       return notExistBuyer;
        
    }

    @Override
    public List<SupplyArea0Vo> getCustomSupplyArea0(String shopProductId) {
        return directionalDao.getCustomSupplyArea0(shopProductId);
    }

    @Override
    public AreaInfoVo getAreaInfoVo(String areaId) {
        return directionalDao.getAreaInfoVo(areaId);
    }

    @Override
    @Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
    public int insertDirectional(String shopProductId, String priceretailonline, String stockNumber, String areaId,
            String pk_stordoc, String userId, String gifts, String isContainInvoice) {
        return directionalDao.insertDirectional(shopProductId, priceretailonline, stockNumber, areaId, pk_stordoc, userId, gifts, isContainInvoice);
    }

    @Override
    @Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
    public int insertDirectionalForCustom(String shopProductId, String priceretailonline, String stockNumber,
            String customId, String pk_stordoc, String userId, String gifts, String isContainInvoice) {
        return directionalDao.insertDirectionalForCustom(shopProductId, priceretailonline, stockNumber, customId, pk_stordoc, userId, gifts, isContainInvoice);
    }

    @Override
    public List<SupplyArea0Vo> checkIsCustomId(String shopProductId) {
        return directionalDao.checkIsCustomId(shopProductId);
    }

    @Override
    public List<SupplyArea0Vo> checkIsAreaId(String shopProductId) {
        return directionalDao.checkIsAreaId(shopProductId);
    }

    @Override
    public boolean checkProduct(String productId) {
        ProductMainVO vo = productMainDao.getProductMainByProductId(productId);
        return vo != null && !"".equals(StringHelperTools.nvl(vo.getIsInSapSales())) && "1".equals(vo.getIsInSapSales());
    }

    @Override
    @Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
    public int insertDirectionalShare(String shopProId, String priceretailonline, String stockNumber, String areaId,
            String shareCode, String userId, String pk_stordoc, String gifts, String isContainInvoice) {
        return directionalDao.insertDirectionalShare(shopProId, priceretailonline, stockNumber, areaId, shareCode, userId, pk_stordoc, gifts, isContainInvoice);
    }

    @Override
    @Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
    public int insertDirectionalShareForCustom(String shopProId, String priceretailonline, String stockNumber,
            String customId, String shareCode, String userId, String pk_stordoc, String gifts, String isContainInvoice) {
        return directionalDao.insertDirectionalShareForCustom(shopProId, priceretailonline, stockNumber, customId, shareCode, userId, pk_stordoc, gifts, isContainInvoice);
    }

    @Override
    public List<BuyerVo> changeImportBuyer(List<BuyerVo>  supplyId, List<BuyerVo> buyerList) {
        List<BuyerVo> newBuyerList = new ArrayList<BuyerVo>();
        // 查出所有供应商销售区域内的买家
       // List<BuyerVo> list = buyerDao.getBuyerBySupplyId(supplyId);
        for(BuyerVo excelVo : buyerList) {
        	if(!"".equals(excelVo.getShortcompanyname())){
        		for(BuyerVo dbVo : supplyId) {
                    // 若查出的买家公司简称与导入的一致，则将查出的买家信息放入新买家列表中
                	if(!"".equals(dbVo.getShopname())){
                		if(dbVo.getShopname().equals(excelVo.getShortcompanyname())) {
                            newBuyerList.add(dbVo);
                            break;
                        }
                	}
                }
        	}
        }
        return newBuyerList;
    }
    @Override
	public List<BuyerVo> queryBuyerInfoByAreaId(List<String> areaId,Map<String, String> buyerTypeMap) {
		List<BuyerVo> buyerList= new ArrayList<BuyerVo>();
	
	   String strsql="";	
	   
	   if(areaId.size()>1000){
		   
		 int size=	areaId.size()/1000;
		 int mod=areaId.size()%1000;
		 
		 for(int j=0;j<size;j++){
			  		
		  for(int i=j*1000;i<(j+1)*1000;i++){			  
			if(i==(j+1)*1000-1){
				strsql=strsql+areaId.get(i);
			  }else{
				strsql=strsql+areaId.get(i)+",";
			  }
			
			System.out.println("--"+(j+1)*1000);
			
		   }		  
		  buyerList.addAll(  buyerDao.queryBuyerInfoByAreaId(strsql,buyerTypeMap) );	
		  strsql="";	
		}
		 
		 for(int i=size*1000;i<size*1000+mod;i++){
			 
				if(i==areaId.size()-1){
					strsql=strsql+areaId.get(i);
				  }else{
					strsql=strsql+areaId.get(i)+",";
				  }	  		
			    }
	     buyerList.addAll(  buyerDao.queryBuyerInfoByAreaId(strsql,buyerTypeMap) );	 
	     
	  }else{
		   
		  for(int i=0;i<areaId.size();i++){
			if(i==areaId.size()-1){
				strsql=strsql+areaId.get(i);
			}else{
				strsql=strsql+areaId.get(i)+",";
			 }
		   }			   
		  buyerList=buyerDao.queryBuyerInfoByAreaId(strsql,buyerTypeMap);		  
	   }
	   
	    System.out.println("用户名的长度"+buyerList.size());
		return buyerList ;
	}

	@Override
	public List<String> queryAreaInfoBySupplyId(List<String> supplyId) {
		
		return buyerDao.queryAreaInfoBySupplyId(supplyId);
	}

    @Override
    public Map<String, String> getBuyerTypeBySupplyType(String supplyType) {
        Map<String,String> buyerType=new HashMap<String,String>();
        Map<String, String> buyerTypeMap = TellingConstance.BUYER_TYPE;
        if(TellingConstance.supply_type01.equals(supplyType)||TellingConstance.supply_type02.equals(supplyType)){
            buyerType.put("01", buyerTypeMap.get("01"));
            buyerType.put("02", buyerTypeMap.get("02"));
            buyerType.put("04", buyerTypeMap.get("04"));
            buyerType.put("05", buyerTypeMap.get("05"));
        }
        if(TellingConstance.supply_type03.equals(supplyType)){
            buyerType.put("01", buyerTypeMap.get("01"));
            buyerType.put("02", buyerTypeMap.get("02"));
            buyerType.put("04", buyerTypeMap.get("04"));
        }
        if(TellingConstance.supply_type04.equals(supplyType)){
            buyerType.put("03", buyerTypeMap.get("03"));
        }
        if(TellingConstance.supply_type05.equals(supplyType)){
        	 buyerType.put("01", buyerTypeMap.get("01"));
        	 buyerType.put("04", buyerTypeMap.get("04"));
        }
        return buyerType;
    }

	@Override
	public List<Map<String, String>> loadProductList(String userId, String sortId1, String sortId2,String productName,String saleType,String status,String leafBrandId,String isLeafBrand) {
		// TODO Auto-generated method stub
		return directionalDao.loadProductList(userId, sortId1, sortId2, productName,saleType,status,leafBrandId,isLeafBrand);
	}

	@Override
	public int doInsert(String supplyId, String ProductId) {
		// TODO Auto-generated method stub
		return directionalDao.doInsert(supplyId, ProductId);
	}

	@Override
	public int doCheck(String supplyId, String ProductId) {
		// TODO Auto-generated method stub
		return directionalDao.doCheck(supplyId, ProductId);
	}

	@Override
	public List<Map<String, String>> findNewProductList(List<Map<String,String>> list,String userId,String saleType) {
		List<Map<String, String>> listProduct= new ArrayList<Map<String,String>>();
		listProduct=directionalDao.queryNewProductList(userId,saleType);
		if(listProduct!=null&&listProduct.size()>0){
			for(Map<String,String> tempMap:list){
				String productId=tempMap.get("productId");
				for(Map<String,String> ctempMap:listProduct){
					String cproductId = ctempMap.get("productId");
					if(!"".equals(productId)&& !"".equals(cproductId)){
						if(cproductId.equals(productId)){
							String shopProductId = ctempMap.get("shopProductId");
							tempMap.put("shopProductId", shopProductId);
							break;
						}
					}else{
						continue;
					}
				}
			}
		}
		return list;
	}
}